<?php

namespace app\common\model\Business;

// 引入tp的模型
use think\Model;

use traits\model\SoftDelete;

// 客户模型
class Business extends Model
{
    use SoftDelete;

    // 数据表
    protected $table = 'pre_business';

    // 开启自动写入时间
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    // 定义软删除字段
    protected $deleteTime = 'deletetime';

    // 追加不存在数据库的字段
    protected $append = [
        // 文字 => text 文件链接 => cdn
        'avatar_cdn',
        'mobile_text',
        'gender_text',
        'region_text',
        'deal_text'
    ];

    // 手机号获取器 mobile_text => MobileText 必须加Attr
    /* 
        value => 数据库存在的字段名
        data => 整条数据 => 一行
    */
    public function getMobileTextAttr($value, $data)
    {
        return substr_replace($data['mobile'], '****', 3, 4);
    }

    // 性别获取器
    public function getGenderTextAttr($value, $data)
    {
        $genderList = ['0' => '保密', '1' => '男', '2' => '女'];

        return $genderList[$data['gender']];
    }

    // 头像获取器
    public function getAvatarCdnAttr($value, $data)
    {
        // 如果头像不存在时给默认头像 ? 有 => http://
        // http://www.k2222.com/uploads/2023/04/08/202304081744.png

        // 获取网站域名
        $cdn = config('site.url');

        $avatar = !empty($data['avatar']) ? $data['avatar'] : '';

        if (!is_file('.' . $avatar)) {
            return $cdn . '/assets/home/images/avatar.jpg';
        }

        return $cdn . $avatar;
    }

    public function getRegionTextAttr($value, $data)
    {

        $District = model('Region')->where(['code' => $data['district']])->find();

        if (!$District) {
            return '';
        }

        $region_text = '';

        if ($District['province']) {
            $region_text = $District['province'] . '-';
        }

        if ($District['city']) {
            $region_text .= $District['city'] . '-';
        }

        if ($District['district']) {
            $region_text .= $District['district'];
        }

        return $region_text;
    }

    public function getDealTextAttr($value, $data)
    {
        $list = [0 => '未成交', 1 => '已成交'];

        return $list[$data['deal']];
    }

    public function source()
    {
        return $this->belongsTo('app\common\model\Business\Source', 'sourceid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
